<template>
  <view class="checkout-page">
    <!-- 收货地址选择 -->
    <view class="address-section" @click="navigateToAddress">
      <view class="address-content" v-if="address.id">
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{ address.name }}</text>
            <text class="phone">{{ address.phone }}</text>
          </view>
          <view class="address-detail">{{ address.province + address.city + address.district + address.detail }}</view>
        </view>
        <view class="arrow">></view>
      </view>
      <view class="empty-address" v-else>
        <text class="add-text">请添加收货地址</text>
        <view class="arrow">></view>
      </view>
      <view class="address-divider"></view>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-section">
      <view class="section-title">商品清单</view>
      <view class="product-list">
        <view class="product-item" v-for="(item, index) in orderItems" :key="index">
          <image class="product-image" :src="item.image" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{ item.name }}</view>
            <view class="product-spec">{{ item.spec }}</view>
            <view class="price-info">
              <text class="price">{{ item.price.toFixed(2) }}</text>
              <text class="quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 配送方式 -->
    <view class="delivery-section">
      <view class="section-item">
        <text class="item-label">配送方式</text>
        <view class="item-value">
          <text>普通快递</text>
          <text class="delivery-fee">{{ deliveryFee > 0 ? '￥' + deliveryFee.toFixed(2) : '免运费' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-section">
      <view class="section-title">支付方式</view>
      <view class="payment-option" v-for="(payment, index) in paymentOptions" :key="index" @click="selectPayment(payment.value)">
        <view class="payment-name">
          <image class="payment-icon" :src="payment.icon"></image>
          <text class="name">{{ payment.name }}</text>
        </view>
        <view class="radio" :class="{ checked: payment.value === selectedPayment }">
          <text v-if="payment.value === selectedPayment">✓</text>
        </view>
      </view>
    </view>
    
    <!-- 金额明细 -->
    <view class="amount-section">
      <view class="amount-item">
        <text class="label">商品金额</text>
        <text class="value">{{ productAmount.toFixed(2) }}</text>
      </view>
      <view class="amount-item">
        <text class="label">运费</text>
        <text class="value">{{ deliveryFee > 0 ? deliveryFee.toFixed(2) : '免运费' }}</text>
      </view>
      <view class="amount-item border-top">
        <text class="label">合计</text>
        <text class="value primary">{{ totalAmount.toFixed(2) }}</text>
      </view>
    </view>
    
    <!-- 订单备注 -->
    <view class="remark-section">
      <view class="section-title">订单备注</view>
      <textarea class="remark-input" v-model="remark" placeholder="选填，可填写您的特殊需求" maxlength="100" />
    </view>
    
    <!-- 底部提交栏 -->
    <view class="bottom-bar">
      <view class="total-info">
        <text class="price-desc">合计：</text>
        <text class="total-price">{{ totalAmount.toFixed(2) }}</text>
      </view>
      <view class="submit-btn" @click="submitOrder">提交订单</view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import orderApi from '@/api/order.js';
import userApi from '@/api/user.js';
import '@/styles/pages/order/checkout.scss';

export default {
  data() {
    return {
      orderItems: [],
      address: {},
      remark: '',
      deliveryFee: 0,
      selectedPayment: 'wxpay',
      paymentOptions: [
        {
          name: '微信支付',
          value: 'wxpay',
          icon: '/static/images/icons/wxpay.png'
        },
        {
          name: '支付宝支付',
          value: 'alipay',
          icon: '/static/images/icons/alipay.png'
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      defaultAddress: 'user/defaultAddress',
      cartItems: 'cart/cartItems'
    }),
    productAmount() {
      return this.orderItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    },
    totalAmount() {
      return this.productAmount + this.deliveryFee;
    }
  },
  onLoad(options) {
    // 从购物车或商品详情页跳转过来
    if (options.from === 'cart') {
      // 从购物车结算
      this.orderItems = this.cartItems.filter(item => item.selected);
    } else if (options.items) {
      // 从商品详情页立即购买
      try {
        this.orderItems = JSON.parse(decodeURIComponent(options.items));
      } catch(e) {
        console.error('解析订单商品数据失败', e);
      }
    }
    
    // 获取默认地址
    this.getAddress();
    
    // 计算运费
    this.calculateDeliveryFee();
  },
  methods: {
    ...mapActions({
      clearCartItemsAction: 'cart/clearSelectedItems'
    }),
    
    // 获取默认地址
    async getAddress() {
      try {
        // 获取默认收货地址
        const res = await userApi.getDefaultAddress();
        this.address = res || {};
      } catch (error) {
        console.error('获取默认地址失败', error);
        this.address = {};
      }
    },
    
    // 计算运费
    calculateDeliveryFee() {
      // 根据商品计算运费
      const totalQuantity = this.orderItems.reduce((total, item) => total + item.quantity, 0);
      
      // 模拟运费计算规则
      if (this.productAmount >= 99) {
        this.deliveryFee = 0; // 满99免运费
      } else {
        this.deliveryFee = 8; // 基础运费8元
        
        // 超过3件商品，每增加1件增加2元运费
        if (totalQuantity > 3) {
          this.deliveryFee += (totalQuantity - 3) * 2;
        }
      }
    },
    
    // 前往地址选择页
    navigateToAddress() {
      uni.navigateTo({
        url: '/pages/address/list?from=checkout',
        events: {
          // 监听地址选择
          selectAddress: (addr) => {
            this.address = addr;
          }
        }
      });
    },
    
    // 选择支付方式
    selectPayment(payment) {
      this.selectedPayment = payment;
    },
    
    // 提交订单
    async submitOrder() {
      // 验证地址
      if (!this.address.id) {
        uni.showToast({
          title: '请先选择收货地址',
          icon: 'none'
        });
        return;
      }
      
      // 验证商品
      if (this.orderItems.length === 0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '提交订单中...'
      });
      
      try {
        // 构建订单数据
        const cartIds = this.orderItems.map(item => item.id);
        
        const orderData = {
          addressId: this.address.id,
          cartIds: cartIds,
          remark: this.remark,
          paymentMethod: this.selectedPayment
        };
        
        // 创建订单
        const res = await orderApi.createOrder(orderData);
        
        // 清空购物车中已选商品
        this.clearCartItemsAction();
        
        uni.hideLoading();
        
        // 支付订单
        this.payOrder(res.orderId);
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '创建订单失败',
          icon: 'none'
        });
      }
    },
    
    // 支付订单
    async payOrder(orderId) {
      uni.showModal({
        title: '订单创建成功',
        content: '是否立即支付？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '支付中...'
            });
            
            try {
              await orderApi.payOrder(orderId, this.selectedPayment);
              
              uni.hideLoading();
              uni.showToast({
                title: '支付成功',
                icon: 'success'
              });
              
              // 延迟跳转到订单详情页
              setTimeout(() => {
                uni.redirectTo({
                  url: `/pages/order/detail?id=${orderId}`
                });
              }, 1500);
            } catch (error) {
              uni.hideLoading();
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              });
              
              // 跳转到订单列表页
              setTimeout(() => {
                uni.redirectTo({
                  url: '/pages/order/list?status=1'
                });
              }, 1500);
            }
          } else {
            // 跳转到订单列表页
            uni.redirectTo({
              url: '/pages/order/list?status=1'
            });
          }
        }
      });
    }
  }
};
</script> 